<template>
  <div>
    <div
      :class="[isWinter && isHomePage ? 'tempTitle' : 'hidden']"
      class="header-text"
    >
      全国冬季预测：<span style="color: #3a8ee6">{{
        totalTempValue.toFixed(2)
      }}</span
      >&nbsp;亿方
    </div>

    <!--  地图  -->
    <div ref="charts" class="midtop" />

    <!-- 管道路线选择   -->
    <div v-if="!isHomePage" class="pipeSelectDiv">
      <pipe-selected
        @listen="handlerSelectLine"
        :select-pipe="selectPipe"
        :selectPipeLineId="selectPipeLineId"
      />
    </div>

    <!--  温度调节  -->
    <div v-if="isWinter && isHomePage">
      <temp-control @listen="updateTemp" />
    </div>

    <!--  预测图  -->
    <div v-if="!isHomePage">
      <predict-chart
        :target-id="targetId"
        :area="area"
        :selectPipeLineId="selectPipeLineId"
      />
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import china from "../../public/lib/chinaarea.json";
import {
  getCitySeries,
  getGeoConfig,
  getPipeSeries,
  getUserSeries,
  getDataSeries,
  getWinterForecast
} from "@/utils/chartSeriesUtil";
import { winterForecast } from "@/utils/winterForecastData";
import {
  cityData,
  userData,
  cityMarkData,
  userMarkData,
  pipeSystemData,
  pressureData,
  presMarkData
} from "@/utils/LatData";
import {
  getAreaDataById,
  getAreaIngasDataById,
  getAreaOutgasDataById,
  getCityOutgasDataById,
  getCityOutgasDataByIdMock,
  getPipeIngasDataById,
  getPipeOutgasDataById,
  getUserOutgasDataById,
  getWinterForecastData
} from "@/api/dashboard";
import PredictChart from "@/views/PredictChart.vue";
import PipeSelected from "@/views/PipeSelected.vue";
import TempControl from "@/views/TempControl.vue";
import store from "@/store/index";
export default {
  components: { PredictChart, PipeSelected, TempControl },
  data() {
    return {
      mapChart: null,
      predictTime: "",
      cons: {
        markPoint: "markPoint",
        scatter: "scatter",
        geo: "geo",
        outGas: "预测出气量：",
        outGasUnit: "万方"
      },
      mapOptions: null,
      isShowAllCity: true,
      totalTempValue: 0,
      isWinter: true,
      isHomePage: true,
      bock: "",
      cityPointDefaultSize: [16, 16],
      userPointDefaultSize: [16, 16],
      userPointMaxSize: [16, 16],
      pipeLinesDefaultWidth: 2,
      zoomData: {
        20: {
          name: "东部",
          center: [117.258018, 31.082783],
          zoom: 3,
          textStyle: {
            fontSize: 14, // 字体大小
            color: "rgba(32, 60, 98, 1)", // 字体颜色
            fontFamily: "PingFangSC-Medium", // 字体
            fontWeight: 500, // 字体粗细
            textAlign: "left", // 文本对齐
            lineHeight: 18, // 行高
            whiteSpace: "nowrap", // 不换行
            overflowWrap: "break-word", // 溢出处理
            textBorderColor: "#fff", // 边框颜色
            textBorderWidth: 2, // 边框宽度
            textShadowColor: "#000", // 阴影颜色
            textShadowBlur: 5 // 阴影模糊程度
          }
        },
        21: {
          name: "中部",
          center: [112.033186, 25.416939],
          zoom: 3,
          textStyle: {
            fontSize: 14, // 字体大小
            color: "rgba(32, 60, 98, 1)", // 字体颜色
            fontFamily: "PingFangSC-Medium", // 字体
            fontWeight: 500, // 字体粗细
            textAlign: "left", // 文本对齐
            lineHeight: 18, // 行高
            whiteSpace: "nowrap", // 不换行
            overflowWrap: "break-word", // 溢出处理
            textBorderColor: "#fff", // 边框颜色
            textBorderWidth: 2, // 边框宽度
            textShadowColor: "#000", // 阴影颜色
            textShadowBlur: 5 // 阴影模糊程度
          }
        },
        23: {
          name: "北部",
          center: [121.011067, 36.842312],
          zoom: 3,
          textStyle: {
            fontSize: 14, // 字体大小
            color: "rgba(32, 60, 98, 1)", // 字体颜色
            fontFamily: "PingFangSC-Medium", // 字体
            fontWeight: 500, // 字体粗细
            textAlign: "left", // 文本对齐
            lineHeight: 18, // 行高
            whiteSpace: "nowrap", // 不换行
            overflowWrap: "break-word", // 溢出处理
            textBorderColor: "#fff", // 边框颜色
            textBorderWidth: 2, // 边框宽度
            textShadowColor: "#000", // 阴影颜色
            textShadowBlur: 5 // 阴影模糊程度
          }
        },
        24: {
          name: "南部",
          center: [110.046278, 19.329091],
          zoom: 3,
          textStyle: {
            fontSize: 14, // 字体大小
            color: "rgba(32, 60, 98, 1)", // 字体颜色
            fontFamily: "PingFangSC-Medium", // 字体
            fontWeight: 500, // 字体粗细
            textAlign: "left", // 文本对齐
            lineHeight: 18, // 行高
            whiteSpace: "nowrap", // 不换行
            overflowWrap: "break-word", // 溢出处理
            textBorderColor: "#fff", // 边框颜色
            textBorderWidth: 2, // 边框宽度
            textShadowColor: "#000", // 阴影颜色
            textShadowBlur: 5 // 阴影模糊程度
          }
        },
        25: {
          name: "西部",
          center: [95.080077, 38.161449],
          zoom: 2,
          textStyle: {
            fontSize: 14, // 字体大小
            color: "rgba(32, 60, 98, 1)", // 字体颜色
            fontFamily: "PingFangSC-Medium", // 字体
            fontWeight: 500, // 字体粗细
            textAlign: "left", // 文本对齐
            lineHeight: 18, // 行高
            whiteSpace: "nowrap", // 不换行
            overflowWrap: "break-word", // 溢出处理
            textBorderColor: "#fff", // 边框颜色
            textBorderWidth: 2, // 边框宽度
            textShadowColor: "#000", // 阴影颜色
            textShadowBlur: 5 // 阴影模糊程度
          }
        }
      },
      areaSubList: {},
      outgasDataMap: new Map(),
      timer: 0,
      targetId: "23",
      winterForecast: winterForecast,
      id: 23,
      area: null,
      selectPipe: {},
      selectPipeLineId: "0",
      transformedLinesData: [],
      pressureData: []
    };
  },
  watch: {
    mapOptions: {
      deep: true,
      handler() {
        this.setMapChartOptions();
      }
    },
    "$store.state.app.curTime": {
      deep: true,
      handler() {
        this.predictTime = store.state.app.curTime;
        // 清除上一次延时器
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.updateMarkOutgasData(true);
        }, 300);
      }
    },
    isHomePage: {
      deep: true,
      handler(newVal, oldVal) {
        if (!newVal) {
          // 可以做成watch监听
          this.mapOptions.geo.roam = !this.isHomePage;
          this.mapOptions.series[0].symbolSize = this.cityPointDefaultSize;
          this.mapOptions.series[0].markPoint.symbolSize = 1;
          this.mapOptions.series[1].symbolSize = 1;
          this.mapOptions.series[1].markPoint.symbolSize = 1;
          this.mapOptions.series[2].polyline = true;
          this.mapOptions.series[2].show = true;
          if (this.mapOptions.series[2].lineStyle) {
            this.mapOptions.series[2].lineStyle.width = this.pipeLinesDefaultWidth;
          }

          if (this.mapOptions.series[3]) {
            this.mapOptions.series[3].label.show = false;
          }
          if (this.mapOptions.series[4]) {
            this.mapOptions.series[4].markPoint.symbolSize = 1;
            this.mapOptions.series[4].symbolSize = this.userPointDefaultSize;
          }
        } else {
          this.mapOptions.geo.roam = !this.isHomePage;
          this.mapOptions.series[0].symbolSize = 0;
          this.mapOptions.series[0].markPoint.symbolSize = 0;
          this.mapOptions.series[1].symbolSize = 0;
          this.mapOptions.series[1].markPoint.symbolSize = 0;
          this.mapOptions.series[2].polyline = false;
          this.mapOptions.series[2].show = false;
          if (this.mapOptions.series[2].lineStyle) {
            this.mapOptions.series[2].lineStyle.width = 0;
          }

          if (this.mapOptions.series[3]) {
            this.mapOptions.series[3].label.show = true;
          }
          if (this.mapOptions.series[4]) {
            this.mapOptions.series[4].markPoint.symbolSize = 0;
            this.mapOptions.series[4].symbolSize = 0;
          }
        }
      }
    }
  },
  beforeDestroy() {
    if (!this.mapChart) {
      return;
    }
    this.mapChart.dispose();
    this.mapChart = null;
  },
  created() {
    this.initWinterForecast();
    this.initAreaSubList();
    this.initGasData();
    // this.initIngasData();
  },
  mounted() {
    this.$store.dispatch("app/setCurTime", "2024-09-13");
    this.totalTempValue = this.calculateInitialTemp(5);
    this.initLatLngConfig();

    // this.areaSubList = getAreaDataByIdMock({})
    // this.initOutgasDataMock()

    this.initOptions();
    this.initMarkOutgasData();
    this.initCharts();
    this.hiddenMarkPoint();
    // this.isHomePage = false
  },
  methods: {
    initLatLngConfig() {
      for (let i = 0; i < cityMarkData[this.targetId].length; i++) {
        cityMarkData[this.targetId][i].label = { show: true };
      }
      for (let i = 0; i < userMarkData[this.targetId].length; i++) {
        userMarkData[this.targetId][i].label = { show: false };
        userData[this.targetId][i].label = { show: false };
      }
      for (let i = 0; i < pressureData[this.targetId].length; i++) {
        pressureData[this.targetId][i].label = { show: false };
        presMarkData[this.targetId][i].label = { show: false };
      }
    },
    initOutgasDataMock() {
      const params = {
        cityId: "10",
        dispatcherId: this.targetId
      };
      const res = getCityOutgasDataByIdMock(params);
      this.setDataMap(res.data, "10");
    },

    // 冬季保供
    initWinterForecast() {
      getWinterForecastData().then(res => {
        if (res.code !== 200) {
          return;
        }
        this.winterForecast = res.data;
        this.initOptions();
        this.totalTempValue = this.calculateInitialTemp(5);
      });
    },
    initGasData() {
      // 初始化大区出气量数据
      const param = {
        dispatcherId: this.targetId
      };
      getAreaOutgasDataById(param).then(res => {
        if (res.code !== 200) {
          return;
        }
        this.setDataMap(res.data, this.targetId);
        console.log("北部大区出气数据加载完毕");
        this.setStoreOutGasData(res.data, this.targetId);
      });

      // 初始化管道系统出气量数据
      // todo

      // 初始化城市出气量数据
      for (const city of cityData[this.targetId]) {
        const params = {
          cityId: city.id,
          dispatcherId: this.targetId
        };

        getCityOutgasDataById(params).then(res => {
          if (res.code !== 200) {
            return;
          }
          this.setDataMap(res.data, city.id);
          console.log(city.name + " 城市出气数据加载完毕");
          this.setStoreOutGasData(res.data, city.id);
        });
      }

      // 初始化用户出气量数据
      for (const user of userData[this.targetId]) {
        const params = {
          userId: user.id,
          dispatcherId: this.targetId
        };

        getUserOutgasDataById(params).then(res => {
          if (res.code !== 200) {
            return;
          }
          this.setDataMap(res.data, user.id);
          console.log(user.name + " 用户出气数据加载完毕");
          this.setStoreOutGasData(res.data, user.id);
        });
      }
    },
    initIngasData() {
      // 初始化大区管存量数据
      const param = {
        dispatcherId: this.targetId
      };
      getAreaIngasDataById(param).then(res => {
        if (res.code !== 200) {
          return;
        }
        this.setStoreInGasData(res.data, "23");
      });

      // 初始化管道系统管存量数据
      for (const pipeSyc of pipeSystemData) {
        const params = {
          pipelineId: pipeSyc.id,
          dispatcherId: this.targetId
        };
        localStorage.setItem("pipelineId", pipeSyc.id);
        getPipeIngasDataById(params).then(res => {
          if (res.code !== 200) {
            return;
          }
          this.setStoreInGasData(res.data, pipeSyc.id);
        });
      }
    },
    setStoreOutGasData(data, id) {
      this.$store.dispatch("app/setOutgasData", {
        id: id,
        data: data
      });
    },
    setStoreInGasData(data, id) {
      if (!data) {
        return;
      }

      for (let key in data.oneDay) {
        if (data.oneDay[key] === null || data.oneDay[key] === "") {
          data.oneDay[key] = "0";
        }
      }
      for (let key in data.fifteenDay) {
        if (data.fifteenDay[key] === null || data.fifteenDay[key] === "") {
          data.fifteenDay[key] = "0";
        }
      }
      this.$store.dispatch("app/setIngasData", {
        id: id,
        data: data
      });
    },
    setDataMap(data, id) {
      if (data) {
        const valueList = [].concat(
          data.fifteenDay.resultList,
          data.fifteenDay.resultListZs,
          data.oneDay.accumulativeList,
          data.oneDay.ycList
        );
        for (const val of valueList) {
          this.outgasDataMap.set(id + "=" + val.time, val.value);
        }
      }
    },
    initAreaSubList() {
      const params = {
        dispatcherId: this.targetId
      };
      getAreaDataById(params).then(res => {
        if (res.code !== 200) {
          return;
        }
        this.areaSubList = res.data;
      });
    },
    initMarkOutgasData() {
      // this.predictTime = '2024-09-13'
      this.updateMarkOutgasData(false);
    },
    initOptions() {
      // const userSymbolSize = this.isSelected ? [30, 30] : [20, 20]; // 示例变量，表示选中状态

      this.mapOptions = {
        geo: getGeoConfig(),
        series: [
          getCitySeries(
            cityData[this.targetId],
            cityMarkData[this.targetId],
            "{b}" + "\n" + this.cons.outGas + "{c}" + this.cons.outGasUnit
          ),
          getUserSeries(
            userData[this.targetId],
            userMarkData[this.targetId],
            "{b}" + "\n" + this.cons.outGas + "{c}" + this.cons.outGasUnit
          ),
          getWinterForecast(0, this.winterForecast)
        ]
      };
      console.log(this.mapOptions, "==================");
    },
    initCharts() {
      this.mapChart = echarts.init(this.$refs["charts"]);
      echarts.registerMap("china", china);
      this.setMapChartOptions();

      const cxt = this;
      this.mapChart.on("click", function(params) {
        cxt.bindMarkPointClick(params);
        cxt.bindGeoAreaClick(params);
        cxt.bindGetMapList(params);
      });
    },
    setMapChartOptions() {
      this.mapChart.setOption(this.mapOptions);
    },
    //切换二级菜单
    bindGetMapList(params) {
      if (params.componentType != "geo") {
        return;
      }
      getAreaDataById({
        dispatcherId: params.region.id
      }).then(res => {
        if (res.code == "200") {
          this.selectPipe = res.data;
          this.areaSubList = res.data;
          const transData = this.transPipeLineData(res.data);

          this.transformedLinesData = transData;
          this.updateLineDataOotions(transData);
          this.setMapChartOptions();
        }
      });
    },
    bindMarkPointClick(params) {
      console.log(params);
      if (params.componentType == "geo") {
        localStorage.setItem("adcode", params.name);
        localStorage.setItem("id", params.region.id);
      } else {
        localStorage.setItem("adcode", params.data.id);
        localStorage.setItem("id", params.data.id);
      }
      if (params.componentSubType !== this.cons.scatter) {
        return;
      }
      this.setMapGeoCenter(
        this.mapChart.getOption().geo[0].center,
        this.mapChart.getOption().geo[0].zoom
      );
      const labelData = this.mapOptions.series[params.seriesIndex].markPoint
        .data[params.dataIndex].label;
      this.targetId = params.data.id;
      if (labelData) {
        const isShow = labelData.show;
        // 先隐藏所有弹窗
        this.hiddenMarkPoint();
        // 切换被点击的弹窗显示状态
        const bool = this.isShowAllCity || !isShow;
        labelData.show = bool;
        if (params.seriesIndex === 1) {
          this.mapOptions.series[1].data[params.dataIndex].label.show = bool;
        }
        this.isShowAllCity = false;
      }
    },

    // 监听点击地图切换大区数据
    bindGeoAreaClick(params) {
      this.area = params.name;
      if (params.componentType !== this.cons.geo) {
        return;
      }
      if (params.region) {
        this.targetId = params.region.id;
      }
      this.targetId = String(params.region.id);
      this.hideWinterForecastLabel();
      this.userActionTriggerOptionsUpdate({
        center: this.zoomData[params.region.id].center,
        zoom: this.zoomData[params.region.id].zoom
      });
      this.hiddenMarkPoint();
      this.mapOptions.series[0].markPoint.data[0].label.show = true;
      this.mapOptions.series[1].symbolSize = 0;
      const regions = this.mapOptions.geo.regions;
      for (let i = 0; i < regions.length; i++) {
        if (params.region.id === regions[i].id) {
          regions[i].itemStyle.areaColor = "#E4EFFD";
          regions[i].emphasis.itemStyle.areaColor = "#E4EFFD";
        } else {
          regions[i].itemStyle.areaColor = "#FFFFFF";
        }
      }
      this.isHomePage = false;

      this.setMapChartOptions();
    },

    hiddenMarkPoint() {
      //  todo 性能优化
      for (let sIndex = 0; sIndex < this.mapOptions.series.length; sIndex++) {
        if (this.mapOptions.series[sIndex].type !== this.cons.scatter) {
          continue;
        }
        for (
          let dIndex = 0;
          dIndex < this.mapOptions.series[sIndex].markPoint.data.length;
          dIndex++
        ) {
          if (this.mapOptions.series[sIndex].markPoint.data[dIndex].label) {
            if (
              this.mapOptions.series[sIndex].markPoint.data[dIndex].label.show
            ) {
              this.mapOptions.series[sIndex].markPoint.data[
                dIndex
              ].label.show = false;
            }
          }
        }
      }
      for (
        let dIndex = 0;
        dIndex < this.mapOptions.series[1].data.length;
        dIndex++
      ) {
        if (this.mapOptions.series[1].data[dIndex]) {
          this.mapOptions.series[1].data[dIndex].label.show = false;
        }
      }
    },
    handlerSelectLine(lineId) {
      console.log("handlerSelectLine ----> ", this.selectPipeLineId, lineId);
      const localSelectPipeLineId = this.selectPipeLineId;
      this.selectPipeLineId = String(lineId);

      // 取消所有管线的高亮
      this.mapChart.dispatchAction({
        type: "downplay",
        seriesIndex: 3
      });

      if (localSelectPipeLineId === lineId) {
        this.clickSamePipeLine();
        return;
      }

      // 重置重点用户、城市、关键点、label等的配置
      this.userActionTriggerOptionsUpdate({
        center: this.zoomData[this.targetId]
          ? this.zoomData[this.targetId].center
          : null,
        zoom: this.zoomData[this.targetId].zoom
      });
      this.highlightPipeline(lineId);

      // 展示管线下的重点用户信息
      this.showLineUserData(lineId);

      // 先隐藏所有弹窗
      this.hiddenMarkPoint();
      // 重新用新配置渲染地图
      this.setMapChartOptions();
    },
    // 重复点击了一条管线, 重置关键用户的label展示
    clickSamePipeLine() {
      this.mapOptions.series[1].label.show = false;

      for (let i = 0; i < userMarkData[this.targetId].length; i++) {
        this.mapOptions.series[1].data[
          i
        ].symbolSize = this.userPointDefaultSize;
      }
    },
    highlightPipeline(selectedLineId) {
      const [beSystemPipeline, subPipelineList] = this.isPipelineSystem(
        selectedLineId
      );

      if (beSystemPipeline) {
        subPipelineList.forEach(inSystempipeLineid => {
          this.highlightSinglePipeline(inSystempipeLineid);
        });
        this.getPipelineSystemKeyPoints(subPipelineList).then((resp) => {
          const [ keyPoints, keyPointsMark ] = resp;
          this.setPipelineKeyPoints(keyPoints, keyPointsMark);
        })
      } else {
        this.highlightSinglePipeline(selectedLineId);
        this.getSinglePipelineKeyPoints(selectedLineId).then((resp) => {
          const [ keyPoints, keyPointsMark ] = resp;
          this.setPipelineKeyPoints(keyPoints, keyPointsMark);
        });
      }
    },

    // 高亮具体的某一条管线
    highlightSinglePipeline(lineId) {
      const selectedPipeArr = [];
      // 高亮管道线路
      for (let i = 0; i < this.transformedLinesData.length; i++) {
        if (
          this.transformedLinesData[i].id === lineId ||
          this.transformedLinesData[i].group === lineId
        ) {
          selectedPipeArr.push(i);
        }
      }
      this.mapChart.dispatchAction({
        type: "highlight",
        seriesIndex: 3,
        dataIndex: selectedPipeArr
      });
    },

    // 设置管线下的关键点的展示情况
    setPipelineKeyPoints(keyPoints, keyPointsMark) {
      // 设置这条或这个系统管线下的关键点的样式
      this.mapOptions.series[4] = getDataSeries(keyPoints, keyPointsMark);
      this.mapOptions.series[4].show = true;
      // 设置进气图标的大小
      this.mapOptions.series[4].symbolSize = this.userPointDefaultSize;
      this.setMapChartOptions();
    },

    // 判断选择的管线选项是否对应的是系统管线，是的话需要展示和高亮该系统下的所有管线
    isPipelineSystem(selectedLine) {
      const { pipelineList } = this.areaSubList;
      let beSystemPipelineResult = false;
      let subPipelineListResult = [];

      if (pipelineList && pipelineList.length > 0) {
        for (const index in pipelineList) {
          const {
            beSystemPipeline,
            subPipelineList,
            pipelineId
          } = pipelineList[index];
          if (beSystemPipeline && pipelineId === selectedLine) {
            beSystemPipelineResult = beSystemPipeline;
            subPipelineListResult = subPipelineList;
            break;
          }
        }
      }
      return [beSystemPipelineResult, subPipelineListResult];
    },
    
    // 从本地数据里进行匹配获取关键点的坐标值
    getLocalKeypoint(keyPointId) {
      const areaKeyPoints = pressureData[this.targetId];
      if (areaKeyPoints && areaKeyPoints.length > 0) {
        for (const index in areaKeyPoints) {
          const { id } = areaKeyPoints[index];
          if (id === keyPointId) {
            return areaKeyPoints[index];
          }
        }
      }
      return {};
    },

    // 获取系统管线下对应的关键点信息
    getPipelineSystemKeyPoints(subPipelineListResult) {
      return new Promise((reslove, reject) => {
        let pipelineSystemKeyPoints = [];
        let pipelineSystemKeyPointsMark = [];

        const promises = [];
        for (const index in subPipelineListResult) {
          const promise = getPipeOutgasDataById({
            dispatcherId: this.targetId,
            pipelineId: subPipelineListResult[index]
          });
          promises.push(promise);
        }

        Promise.all(promises).then(responses => {
          if (responses.length > 0) {
            responses.forEach(resp => {
              const { keyPointsPressure } = resp.data;
              console.log('---------------> getPipelineSystemKeyPoints', keyPointsPressure);
              if (keyPointsPressure && keyPointsPressure.length > 0) {
                keyPointsPressure.forEach(pressurePoint => {
                  // TODO 后端需要返回一个关键点对应的坐标值
                  const { keyPointId, keyPointName, pressure } = pressurePoint;

                  // TODO：坐标值现在后端接口还没返回，先从本地数据里进行匹配获取，获取不到的不展示
                  const { value: coord } = this.getLocalKeypoint(keyPointId);

                  const keyPoint = {
                    id: keyPointId,
                    name: keyPointName,
                    value: coord
                  };

                  const keyPointMark = {
                    id: keyPointId,
                    name: keyPointName,
                    coord,
                    value: pressure
                  };
                  pipelineSystemKeyPoints.push(keyPoint);
                  pipelineSystemKeyPointsMark.push(keyPointMark);
                });
              }
            });

            if (pipelineSystemKeyPoints.length === 0) {
               // todo 后端有数据返回的情况下，这段代码逻辑需要去掉，目前是为了演示用。使用的全区域数据进行展示
               pipelineSystemKeyPoints.push(...pressureData[this.targetId]);
              pipelineSystemKeyPointsMark.push(...presMarkData[this.targetId]);
            }

            reslove([pipelineSystemKeyPoints, pipelineSystemKeyPointsMark])
          }
        }).catch((error) => {
          reject(error)
        });
      });
    },

    // 获取单条管线下对应的关键点信息
    getSinglePipelineKeyPoints(selectedLine) {
      return new Promise((resolve, reject) => {
        let pipelineSystemKeyPoints = [];
        let pipelineSystemKeyPointsMark = [];

        getPipeOutgasDataById({
          dispatcherId: this.targetId,
          pipelineId: selectedLine
        }).then((resp) => {
          const { keyPointsPressure } = resp.data;
          if (keyPointsPressure && keyPointsPressure.length > 0) {
            keyPointsPressure.forEach(pressurePoint => {
              // TODO 后端需要返回一个关键点对应的坐标值
              const { keyPointId, keyPointName, pressure } = pressurePoint;

              // TODO：坐标值现在后端接口还没返回，先从本地数据里进行匹配获取，获取不到的不展示
              const coord = this.getLocalKeypointCoord(keyPointId);

              const keyPoint = {
                id: keyPointId,
                name: keyPointName,
                value: coord
              };

              const keyPointMark = {
                id: keyPointId,
                name: keyPointName,
                coord,
                value: pressure
              };
              pipelineSystemKeyPoints.push(keyPoint);
              pipelineSystemKeyPointsMark.push(keyPointMark);
            });
          } else {
            // todo 后端有数据返回的情况下，这段代码逻辑需要去掉，目前是为了演示用。使用的全区域数据进行展示
            pipelineSystemKeyPoints.push(...pressureData[this.targetId]);
            pipelineSystemKeyPointsMark.push(...presMarkData[this.targetId]);
          }
          resolve([pipelineSystemKeyPoints, pipelineSystemKeyPointsMark])
        }).catch((error) => {
          reject(error)
        });
      });
    },

    showLineUserData(selectedLineId) {
      const userIndexMap = new Map();
      for (let i = 0; i < userData[this.targetId].length; i++) {
        this.mapOptions.series[1].data[i].symbolSize = 0;
        this.mapOptions.series[1].data[i].label = {};
        userIndexMap.set(userData[this.targetId][i].id, i);
      }

      this.mapOptions.series[1].data = [];

      // 高亮管道下属的重点用户
      let userListData = [];
      for (let i = 0; i < this.areaSubList.pipelineList.length; i++) {
        if (this.areaSubList.pipelineList[i].pipelineId === selectedLineId) {
          userListData = this.areaSubList.pipelineList[i].userList;
          break;
        }
      }

      if (userListData.length === 0) {
        return;
      }

      const userPoints = [];
      const userPointsMark = [];
      for (let i = 0; i < userListData.length; i++) {
        const { userId, userName, lonLatList } = userListData[i];

        // todo：线上数据没有对应的用户的预测值，所以先从本地读取。后续接口数据补齐数据项后，去除该逻辑
        const localUserData = this.getLocalUserData(userId);
        const coordList = [...lonLatList[0]];
        console.log('------> showLineUserData', lonLatList, coordList);

        const userPoint = {
          id: userId,
          name: userName,
          value: coordList,
          symbolSize: this.userPointDefaultSize,
          label: {
            show: false
          }
        };

        const userPointMark = {
          id: userId,
          name: userName,
          value: localUserData.value,
          coord: coordList
        }

        userPoints.push(userPoint);
        userPointsMark.push(userPointMark);
      }

      this.mapOptions.series[1] = getUserSeries(userPoints, userPointsMark, 
      "{b}" + "\n" + this.cons.outGas + "{c}" + this.cons.outGasUnit)
      this.mapOptions.series[1].label.show = true;
    },

    getLocalUserData(userId) {
      const localUserDatas = userMarkData[this.targetId]

      for(const index in localUserDatas) {
        const userData = localUserDatas[index];
        if (userData && userData.id === userId) {
          return userData;
        }
      }

      return {}
    },

    updateTemp(newTemp) {
      this.totalTempValue = this.calculateInitialTemp(5 + newTemp);
      this.mapOptions.series[2] = getWinterForecast(
        newTemp,
        this.winterForecast
      );
      this.setMapChartOptions();
    },

    // todo 性能优化，被初始化了好多次
    updateMarkOutgasData(isDraw) {
      for (
        let i = 0;
        i < this.mapOptions.series[0].markPoint.data.length;
        i++
      ) {
        const key =
          this.mapOptions.series[0].markPoint.data[i].id +
          "=" +
          this.predictTime;
        if (this.outgasDataMap.has(key)) {
          this.mapOptions.series[0].markPoint.data[
            i
          ].value = this.outgasDataMap.get(key);
          this.mapOptions.series[0].markPoint.data[i].name = this.predictTime;
        }
      }
      for (
        let i = 0;
        i < this.mapOptions.series[1].markPoint.data.length;
        i++
      ) {
        const key =
          this.mapOptions.series[1].markPoint.data[i].id +
          "=" +
          this.predictTime;
        if (this.outgasDataMap.has(key)) {
          this.mapOptions.series[1].markPoint.data[
            i
          ].value = this.outgasDataMap.get(key);
          this.mapOptions.series[1].markPoint.data[i].name = this.predictTime;
        }
      }
      if (isDraw) {
        this.setMapChartOptions();
      }
    },

    // 隐藏冬季预测数据地图展示 Label
    hideWinterForecastLabel() {
      if (this.mapOptions.series[2]) {
        this.mapOptions.series[2].label.show = false;
      }
    },

    // 更新城市的地图显示配置
    updateCityDataOptions() {
      this.mapOptions.series[0] = getCitySeries(
        cityData[this.targetId],
        cityMarkData[this.targetId],
        "{b}" + "\n" + this.cons.outGas + "{c}" + this.cons.outGasUnit
      );
      this.mapOptions.series[0].symbolSize = this.cityPointDefaultSize;
      this.mapOptions.series[0].markPoint.symbolSize = 1;

      if (this.mapOptions.series[0].markPoint.data[0].label) {
        this.mapOptions.series[0].markPoint.data[0].label.show = true;
      }
    },
    // 更新数据之后哦重新render
    updateUserDataOptions() {
      this.mapOptions.series[1] = getUserSeries(
        userData[this.targetId],
        userMarkData[this.targetId],
        "{b}" + "\n" + this.cons.outGas + "{c}" + this.cons.outGasUnit
      );

      this.mapOptions.series[1].symbolSize = this.userPointDefaultSize;
      this.mapOptions.series[1].markPoint.symbolSize = 1;
    },

    updateLineDataOotions(pipeLinesData) {
      if (!pipeLinesData) {
        return;
      }

      console.log("--------------------> updateLineDataOotions", pipeLinesData);

      this.mapOptions.series[3] = getPipeSeries(pipeLinesData, this.targetId);
      this.mapOptions.series[3].polyline = true;
      this.mapOptions.series[3].show = true;

      if (this.mapOptions.series[3].lineStyle) {
        this.mapOptions.series[3].lineStyle.width = this.pipeLinesDefaultWidth;
      }
    },

    // 转换后端数据
    transPipeLineData(pipeLinesData) {
      const { pipelineList } = pipeLinesData;
      const resultPipelineData = [];

      if (pipelineList && pipelineList.length) {
        pipelineList.forEach((pipeLineData, index) => {
          const {
            pipelineId,
            pipelineName,
            pipelineSimpleName,
            show,
            lonLatList
          } = pipeLineData;

          if (lonLatList && lonLatList.length > 0) {
            const lineStyle = { color: "#00c4f0" };

            if (index === 0) {
              lineStyle.size = 10;
            }

            const needShowData = {
              id: pipelineId,
              name: pipelineName,
              shortName: pipelineSimpleName,
              lineStyle: lineStyle,
              coords: lonLatList
            };
            resultPipelineData.push(needShowData);
          }
        });
      }

      return resultPipelineData;
    },

    // 设置缩放
    setMapGeoCenter(center, zoom) {
      this.mapOptions.geo.center =
        center || this.zoomData[this.targetId].center;
      this.mapOptions.geo.zoom = zoom;
      this.mapOptions.geo.roam = !this.isHomePage;
    },

    // 用户操作触发的 options 配置更新
    userActionTriggerOptionsUpdate({ center, zoom }) {
      if (!center) {
        return;
      }
      this.initLatLngConfig();
      this.setMapGeoCenter(center, zoom);
      this.updateCityDataOptions();
      this.updateUserDataOptions();
    },

    calculateInitialTemp(key) {
      let initial = 0;
      for (let i = 0; i < this.winterForecast.length; i++) {
        const gasUsage = parseFloat(
          this.winterForecast[i].temperatureData[key].predictedGasUsage
        );
        if (!isNaN(gasUsage)) {
          // 检查是否为有效数字
          initial += gasUsage;
        }
      }
      return initial;
    }
  }
};
</script>
<style scoped>
.midtop {
  width: 100%;
  height: 100vh;
}

.bockmap {
  position: absolute;
  left: 1.5rem;
  top: 1.5rem;
  z-index: 2;
  width: 1.5rem;
  height: 1.8rem;
}

.tempTitle {
  position: absolute;
  top: 2rem;
  width: 100vw;
  text-align: center;
  font-size: 24px;
}

.hidden {
  display: none;
}

.pipeSelectDiv {
  position: absolute;
  top: 2.81rem;
  right: 0.26rem;
  margin: 0;
  height: 30vh;
  width: 55px;
  background: transparent;
}

.header-text {
  font-size: 16px;
  font-family: 苹方-简 中黑体 !important;
  font-weight: 500;
  /* text-align: left; */
  white-space: nowrap;
  line-height: 20px;
}
</style>
